<template>
  <div class="login">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>Gremlin-学生管理系统</span>
      </div>
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="form"
        ref="form"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-button type="primary" @click="submitForm('form')">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { nameRule, passRule } from '@/utils/validate'
import { setToken } from '@/utils/token'
import { login } from '@/api/api'

export default {
  data () {
    return {
      labelPosition: "left",
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [{ validator: nameRule, trigger: 'blur' }],
        password: [{ validator: passRule, trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          login(this.form).then(res => {
            if (res.data.status === 200) {
              setToken('username', res.data.username)
              setToken('token', res.data.token)
              this.$message({ message: res.data.message, type: 'success' })
              this.$router.push('/home')
            } else {
              this.$router.push('/404')
            }
            console.log(res)
          })
        } else {
          console.log(this.form)
        }
      })
    }
  }
}
</script>

<style lang="less">
.login {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: rgb(107, 107, 159);
  .box-card {
    width: 450px;
    margin: 200px auto;
    background-color: rgba(255, 255, 255, 0.7);
    .clearfix {
      font-size: 25px;
      font-weight: 700;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>